#define _CRT_SECURE_NO_WARNINGS 1

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int MAX_N = 100;

int graph[MAX_N][MAX_N];
int n;

void breadthFirstSearch(int startNode, vector<bool>& visited) 
{
    //vector<bool> visited(n, false);
    queue<int> q;

    q.push(startNode);
    visited[startNode] = true;

    while (!q.empty()) 
    {
        int node = q.front();
        q.pop();
        cout << node << " ";

        for (int i = 0; i < n; i++) 
        {
            if (graph[node][i] == 1 && !visited[i]) 
            {
                q.push(i);
                visited[i] = true;
            }
        }
    }
}

int main() 
{
    int t;
    cin >> t;

    for (int test = 0; test < t; test++) 
    {
        cin >> n;

        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                cin >> graph[i][j];
            }
        }

        vector<bool> visited(n, false);

        for (int i = 0; i < n; i++) 
        {
            if (!visited[i])
            {
                breadthFirstSearch(i, visited);
                cout << endl;
            }

        }
    }

    return 0;
}
